<?php

namespace App\Http\Controllers\admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;

class HelpController extends Controller
{
	public function index (Request $request)
	{
		// 定义一个空数组
		$where = [];
		$db = DB::table('help_articles');
		$db->join('help_cates','help_articles.help_cate_id','=','help_cates.id')
		->select('help_articles.*','help_cates.name','help_cates.pid','help_cates.path')
		->get();
		// 查询搜索框
		if($request->has('keywords')){
            $name = $request->input('keywords');
            // dd($name);
            $db->where('help_articles.title','like',"%{$name}%");

            $where['title'] = $name;
        };    	
        // 分页
        $list = $db->paginate(5);
        // dd($list);
		return view('admin.help.index',['list'=>$list,'where'=>$where]);
	}
	public function create ()
	{
		//调用xoxo方法
		$list = $this->xoxo();
		// dd($list);
		return view('admin.help.add',['list'=>$list]);
	}

	public function xoxo ()
	{
		//查询数据库
        $cates = DB::table('help_cates as a')
                ->select(\DB::raw('a.*,b.name as names,concat(a.path,",",a.id,",") as paths'))
                ->leftJoin('help_cates as b','a.pid','=','b.id')
                ->orderBy('paths')
                ->where('a.status',1)
                ->get();
        foreach($cates as $k=>$v){
            $num = substr_count($v->path,',');
            if($num==1){
                $str = '|----';
            }else if($num>1){
                $str = str_repeat('|　　',$num);
                $str .= '|----';
            }else{
                $str = '';
            }
            
            $v->name = $str.$v->name;
        }
        return $cates;
	}

	public function store (Request $request)
	{
		// dd($request);
		$messages = [
    		'required' => ':attribute 的字段是必要的',
    	];
    	//
    	$this->validate($request, [
	        'title' => 'required|unique:help_articles|max:16',
	    ],$messages);
	    $name = $request->except('_token');
	    $name = DB::table('help_articles')->insertGetId($name);
	    if($name>0){
	    	return redirect('admin/help_article')->with('msg','添加成功');
	    }
	}
	public function destroy ($id)
	{
		// dd($id);
		$name = DB::table('help_articles')->where('id',$id)->delete();
		if($name>0){
			return redirect('admin/help_article')->with('msg','删除成功');
		}
	}

	public function edit ($id)
	{
		$list= DB::table('help_articles')
		->join('help_cates','help_articles.help_cate_id','=','help_cates.id')
		->select('help_articles.*','help_cates.name','help_cates.pid','help_cates.path')
		->where('help_articles.id',$id)
		->get();
		// dd($list);
		return view('admin.help.edit',['list'=>$list]);
		
	}

	public function update ($id,Request $request)
	{
		$name = $request->only('title','content');
		$list = DB::table('help_articles')->where('id',$id)->update($name);
		if($name>0){
			return redirect('admin/help_article')->with('msg','修改成功');
		}
	}
}
